package com.yehuo.app.controller;

import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yehuo.app.entity.Page;
import com.yehuo.app.model.R;
import com.yehuo.app.entity.Sensitive;
import com.yehuo.app.mapper.SensitiveMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 敏感词管理
 */
@RestController
@RequestMapping("/sensitive")
public class SensitiveController {


    @Resource
    private SensitiveMapper sensitiveMapper;

    /**
     * 新增敏感词列表
     *
     * @param sensitive
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public R add(@RequestBody Sensitive sensitive) {
        int i = sensitiveMapper.insert(sensitive);
        R<Integer> result = new R<>();
        result.setCode(0);
        result.setMsg(i > 0 ? "新增成功" : "新增失败");
        return result;
    }

    /**
     * 查询敏感词列表
     *
     * @param page
     * @return
     */
    @RequestMapping("/list")
    public R list(Page page) {
        //开启分页
        PageHelper.startPage(page.getPage(), page.getLimit());
        List<Sensitive> list = sensitiveMapper.selectList(null);
        PageInfo<Sensitive> pageInfo = new PageInfo<>(list);
        R<Sensitive> result = new R<Sensitive>((int) pageInfo.getTotal(), pageInfo.getList());
        return result;
    }

    /**
     * 删除敏感词
     *
     * @param id
     * @return
     */
    @RequestMapping("/remove/{id}")
    public R remove(@PathVariable("id") Integer id) {
        int i = sensitiveMapper.deleteById(id);
        R<Integer> result = new R<>();
        result.setCode(0);
        result.setMsg(i > 0 ? "删除成功" : "删除失败");
        return result;
    }

    /**
     * 批量删除敏感词
     *
     * @param ids
     * @return
     */
    @RequestMapping("/batchRemove/{ids}")
    public R batchRemove(@PathVariable("ids") String ids) {
        List<Integer> list = new ArrayList<>();
        if (!StringUtils.isEmpty(ids)) {
            String[] split = ids.split(",");
            for (String s : split) {
                list.add(Integer.parseInt(s));
            }
        }
        int i = sensitiveMapper.deleteBatchIds(list);
        R<Integer> result = new R<>();
        result.setCode(0);
        result.setMsg(i > 0 ? "删除成功" : "删除失败");
        return result;
    }
}
